#================================================================================
# Absolut Admin - By: Miauw Mizx & BackRaw
#   ./addons/eventscripts/absolutadmin/absolutadmin.py
#================================================================================

#================================================================================
# Imports
#================================================================================
import es
import cfglib
import gamethread
import re

#================================================================================
# Custom Library Imports
#================================================================================
import aavote
reload(aavote)
import aaauth
reload(aaauth)
import aalog
reload(aalog)
import aaplayerlib
reload(aaplayerlib)
import aanativetoolslib as aant
reload(aant)

#================================================================================
# Addon Information
#================================================================================
info = es.AddonInfo()
info.name        = 'Absolut Admin'
info.version     = 0.1
info.author      = 'Miauw Mizx & BackRaw'
info.url         = 'www.codymathisen.com'
info.basename    = __name__.split(".", 1)[~0].replace(".", "/") # Thanks Adz
info.description = 'Admin system written in Python, with a php/mysql web front end.'

#================================================================================
# Special Thanks List
#================================================================================
# Einlanzers - Helping with miscellaneous things and answering questions <3
# Boondox - Helping me with ideas for AA, and helping me make up decisions P:
# Plural and Wookz - Testing, and finding sounds for me ;3
# Hekar - Nothing? :c
# Chrisber - NativeTools and answering questions >:]
# Wonder - Using part of his strip_player function >;D
# ojii - Formatting functin for parsing a text string into arguments :o
# Mattie - ESP *<]:3
# Ev0 Community - Testing features :>

#================================================================================
# Configuration Variables
#================================================================================


#================================================================================
# Configuration file
#================================================================================
config      = cfglib.AddonCFG(es.getAddonPath(info.basename)+'/absolutadmin.cfg')

config.text('%s - Ver: %s - By: %s'%(info.name, info.version, info.author))
config.text('..addons/eventscripts/absolutadmin/absolutadmin.cfg')
config.text('')
config.text('')

config.text('================================================')
config.text('>> COMMON ABSOLUT ADMIN SERVER VARIABLES =======')
config.text('================================================')

aa_debug        = config.cvar('aa_debug', 0, 'Absolut Admin Debugging\n// 0 = Disabled (default)\n// 1 = Enabled')
aa_url          = config.cvar('aa_url', 'http://www.ev0gaming.com/admins.php', 'The URL of your web based Absolut Admin')
aa_me_enabled   = config.cvar('aa_me_enabled', 1, 'When a player types a sentance with "/me" prefix, they will be displaying an action.')

config.write()

#================================================================================
# Classes
#================================================================================

#================================================================================
# >> Wrappers
#================================================================================
class Wrapper(object):
    def __init__(self):
        self.prefix = '#green[#lightgreenAbsoluteAdmin#green] #default'
    def echo(self, text):
        es.dbgmsg(0, '[AbsoluteAdmin] %s' % text)
    def msg(self, text):
        es.msg('#multi', '%s %s'%(self.prefix, text))
    def tell(self, userid, text):
        es.tell(userid, '#multi', '%s %s'%(self.prefix, text))
    def tell2(self, userid, index, msg):
        es.usermsg('create', 'saytext2','SayText2')
        es.usermsg('write', 'byte', 'saytext2', index)
        es.usermsg('write', 'byte', 'saytext2', 1)
        es.usermsg('write', 'string', 'saytext2', msg)
        es.usermsg('send', 'saytext2', userid)
        es.usermsg('delete', 'saytext2')
    def tell2All(self, index, msg):
        es.usermsg('create', 'saytext2','SayText2')
        es.usermsg('write', 'byte', 'saytext2', index)
        es.usermsg('write', 'byte', 'saytext2', 1)
        es.usermsg('write', 'string', 'saytext2', msg)
        for userid in es.getUseridList():
            es.usermsg('send', 'saytext2', userid)
        es.usermsg('delete', 'saytext2')
        self.echo(msg)
wrapper = Wrapper()

#================================================================================
# Addon Load/Unload
#================================================================================
def load():
    aalog.log('**********************************')
    aalog.log('Initializing Absolut Admin Load.')
    aalog.log('**********************************')
    config.execute(1)
    aaauth.updateAdminList(str(aa_url))
    es.addons.registerSayFilter(_sayFilter)
    aalog.log('Registered Absolut Admin "Say Filter" Successfully.')
    aalog.clean()
    aalog.log('**********************************')
    aalog.log('Loaded Absolut Admin Successfully.')
    aalog.log('**********************************')

def unload():
    aalog.log('**********************************')
    aalog.log('Initializing Absolut Admin Un-Load.')
    aalog.log('**********************************')
    es.addons.unregisterSayFilter(_sayFilter)
    aalog.log('Un-Registered Absolut Admin "Say Filter" Successfully.')
    aalog.log('*************************************')
    aalog.log('Un-Loaded Absolut Admin Successfully.')
    aalog.log('*************************************')

#================================================================================
# Custom Game Events
#================================================================================

# just an example, Miauw, how the new wrapper handles the stuff...
# oh, there is NO ev['es_userindex'] ;) look at my code...
def player_say(ev):
    userid = ev['userid']
    if ev['text'] == 'testvote':
        testvote = aavote.init('aatestvote')
        testvote.create('How are you doing?', ('Good', 'Okay..', 'Terrible', 'God Awful'))
        aalog.log('Vote created: \'How are you doing?\'')
        
    if ev['text'] == 'am i authed':
        name = es.getplayername(userid)
        if aaauth.isAuthed(userid):
            wrapper.tell(userid, 'Yes you are!')
            aalog.log('Player %s is authorized' % name)
        else: 
            wrapper.tell(userid, 'No you are not, gtfo')
            aalog.log('Player %s is not authorized' % name)
            
    if ev['text'] == 'generror':
        aalog.log('Sample error, does not delete on plugin load', 1)
        
    if ev['text'] == 'slaytest':
        index = es.createplayerlist(userid)[int(userid)]['index']
        name = es.getplayername(userid)
        wrapper.tell2All(index, '\x04[Admin]\x03 %s \x01slayed player \x04%s'%(name, name))



def _sayFilter(userid, text, teamonly):
    #text = str(text).replace('"', '', 1)

    text = text[1:-1]
    args = list(format(text))
    length = len(args)
    command = args[0][1:] if args[0].startswith('!') or args[0].startswith('/') else args[0]
    es.msg(args)
    if length:
        if args[0] == '/me':
            if aa_me_enabled:
                index = es.createplayerlist(userid)[int(userid)]['index']
                newtext = ' '.join(map(str, args[1:]))
                wrapper.tell2All(index, '\x01*\x03 %s \x01%s'%(es.getplayername(userid), newtext))
                return (0,None,0)
        elif command == 'tester' and length > 1:
            es.msg(aaplayerlib.filters(args[1]))
        elif command == 'slay' and length > 1:
            targets = aaplayerlib.filters(args[1])
            tlen = len(targets)
            if tlen > 0:
                if tlen > 1:
                    for user in targets:
                        aaplayerlib.getPlayer(user).slay()
                    es.msg('Admin %s slayed all %s players'%(es.getplayername(userid), acronym(args[1])))
                else: 
                    for user in targets:
                        aaplayerlib.getPlayer(user).slay()
                        es.msg('Admin %s slayed player %s'%(es.getplayername(userid), es.getplayername(user)))
            else: es.msg('Player %s does not exsist!'%args[1])
            #player = aaplayerlib.getPlayer(userid).slay()
        elif text == 'strip':
            player = aaplayerlib.getPlayer(userid).strip()
        elif text == 'blind':
            player = aaplayerlib.getPlayer(userid).blind(10)
        elif text == 'earthquake':
            player = aaplayerlib.getPlayer(userid).earthquake(5)
        elif text == 'mute':
            player = aaplayerlib.getPlayer(userid).mute()
        elif text == 'getmute':
            es.msg('Mute State: %s'%aaplayerlib.getPlayer(userid).getMute())
        elif text == 'giveweapons':
            player = aaplayerlib.getPlayer(userid).giveWeapons(['m4a1', 'awp'])
        elif text == 'swap':
            player = aaplayerlib.getPlayer(userid).swapTeam()
        elif text == 'swapkill':
            player = aaplayerlib.getPlayer(userid).swapTeam(True)
        elif text == 'team':
            player = aaplayerlib.getPlayer(userid).changeTeam(2)
        elif text == 'spec':
            player = aaplayerlib.getPlayer(userid).spec()
        elif text == 'kick':
            player = aaplayerlib.getPlayer(userid).kick()
        elif text == 'ban':
            player = aaplayerlib.getPlayer(userid).ban()
        elif text == 'noclip':
            aaplayerlib.getPlayer(userid).setNoclip()
        elif text == 'getnoclip':
            es.msg('Noclip State: %s'%aaplayerlib.getPlayer(userid).getNoclip())
        elif text == 'freeze':
            aaplayerlib.getPlayer(userid).setFreeze()
        elif text == 'getfreeze':
            es.msg('Freeze State: %s'%aaplayerlib.getPlayer(userid).getFreeze())
        elif text == 'gethealth':
            es.msg('Health #: %s'%aaplayerlib.getPlayer(userid).getHealth())
        elif text == 'respawn':
            player = aaplayerlib.getPlayer(userid).respawn()
        elif text == 'slap':
            player = aaplayerlib.getPlayer(userid).slap()
        elif text == 'ninja':
            player = aaplayerlib.getPlayer(userid).setNinja()
        elif text == 'getninja':
            es.msg('Ninja State: %s'%aaplayerlib.getPlayer(userid).getNinja())
        elif text == 'heavy':
            player = aaplayerlib.getPlayer(userid).setHeavy()
        elif text == 'getheavy':
            es.msg('Heavy State: %s'%aaplayerlib.getPlayer(userid).getHeavy())
        elif text == 'speed':
            player = aaplayerlib.getPlayer(userid).setSpeed(5)
        if text == 'ct':
            for p in aaplayerlib.filters('@ct'):
                es.msg('Player %s is on CT'%es.getplayername(p))
            
        if text == 't':
            for p in aaplayerlib.filters('@t'):
                es.msg('Player %s is on T'%es.getplayername(p))
            
        if text == 'specz':
            for p in aaplayerlib.filters('@spec'):
                es.msg('Player %s is on Spec'%es.getplayername(p))

        if text == 'bots':
            for p in aaplayerlib.filters('@bot'):
                es.msg('Player %s is a bot!'%es.getplayername(p))
        if text == 'admins':
            for p in aaplayerlib.filters('@admin'):
                es.msg('Player %s is an admin!'%es.getplayername(p))
        
        if text == 'toptext':
            for player in es.getUseridList():
                es.toptext(userid, 5, '#pink', 'This is sexy purple')
        
        if text == 'beam':
            x,y,z = es.getplayerlocation(userid)
            aant.beam(es.getUseridList(), [x,y,z], [x,y,z+20])
            
        if text == 'beacon':
            x,y,z = es.getplayerlocation(userid)
            aant.beacon(es.getUseridList(), [x,y,z+32])
            gamethread.delayed(.25, aant.beacon2, (es.getUseridList(), [x,y,z+32]))
        if text =='test':
            es.msg(aaplayerlib.filters('@dead'))
        
    return (userid, text, teamonly)

def acronym(short):
    if short == '@admin' or short == '@admins':
        return 'admins'
    elif short == '@bot' or short == '@bots':
        return 'bots'
    elif short == '@ct':
        return 'Counter-Terrorists'
    elif short == '@t':
        return 'Terrorists'
    elif short == '@dead':
        return 'Dead'
    elif short == '@alive':
        return 'Alive'
    elif short == '@spec' or short == '@specs':
        return 'Spectators'
    elif short == '@all':
        return 'All'
    else: return short
    
def format(text):
    for bit in smart_split_re.finditer(text):
        yield bit.group(0)

smart_split_re = re.compile(r'''
    ([^\s"]*"(?:[^"\\]*(?:\\.[^"\\]*)*)"\S*|
     [^\s']*'(?:[^'\\]*(?:\\.[^'\\]*)*)'\S*|
     \S+)''', re.VERBOSE)